package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 发布评论
     */
    public void saveComments(String movementId, String comment) {
        String type = "0205";
        //1.获取操作用户的id
        Long userId = UserHolder.getUserId();
        //2.构造Comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));//发布id
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());//发表时间
        //3.调用api保存评论
        Integer commentCount = commentApi.save(comment1);
//        mqMessageService.sendLogService(userId,type,"comments",movementId);

        log.info("commentCount" + commentCount);
    }

    /**
     * 分页查询列表
     */
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //1.调用api查询评论列表
        List<Comment> list =  commentApi.findComments(movementId,CommentType.COMMENT,page,pagesize);
        //2.判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3.提取所有用户id，调用UserInfoApi查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4.构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null){
                CommentVo vo = CommentVo.init(userInfo, comment);
                //判断是否点赞
                String key = Constants.MOVEMENTS_INTERACT_KEY + vo.getId();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key,hashKey)){
                    vo.setHasLiked(1);
                }else {
                    vo.setHasLiked(0);
                }
                vo.setLikeCount(Math.toIntExact(redisTemplate.opsForHash().size(key)));
                vos.add(vo);
            }
        }
        //5.构造返回值
        return new PageResult(page,pagesize,0l,vos);
    }

    //动态点赞
    public Integer likeComment(String movementId) {
        //1.调用api查看是否点赞
        boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LIKE);
        //2.如果已经点赞
        if (hasComment){
            throw  new BusinessException(ErrorResult.likeError());
        }
        //3.调用api保存数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //4.凭借redis的key,将用户点赞存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    //取消点赞
    public Integer disLikeComment(String movementId) {
        //1.调用api查看是否点赞
        boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LIKE);
        //2.如果已经点赞
        if (!hasComment){
            throw  new BusinessException(ErrorResult.disLikeError());
        }
        //3.调用api保存数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.delete(comment);
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    /**
     * 喜欢
     * @param movementId
     * @return
     */
    public Integer loveComment(String movementId) {
        //1.调用api查看是否点赞
        boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LOVE);
        //2.如果已经点赞
        if (hasComment){
            throw  new BusinessException(ErrorResult.loveError());
        }
        //3.调用api保存数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //4.凭借redis的key,将用户点赞存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    /**
     * 取消喜欢
     * @param movementId
     * @return
     */
    public Integer unLoveComment(String movementId) {
        //1.调用api查看是否点赞
        boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LOVE);
        //2.如果已经点赞
        if (!hasComment){
            throw  new BusinessException(ErrorResult.disloveError());
        }
        //3.调用api保存数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.delete(comment);
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }


    //评论-点赞
    public Integer commentLike(String contentId) {
        //1.查询是否点赞
        String key = Constants.MOVEMENTS_INTERACT_KEY + contentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        if (redisTemplate.opsForHash().hasKey(key,hashKey)){
            throw  new BusinessException(ErrorResult.likeError());
        }
        //3.将点赞存入redis
        redisTemplate.opsForHash().put(key,hashKey,"2");
        //4.修改点赞数+1并返回总数
        Integer size = Math.toIntExact(redisTemplate.opsForHash().size(key));
        return size;
    }
    //评论-取消点赞
    public Integer commentDisLike(String contentId) {
        //1.查询是否点赞
        String key = Constants.MOVEMENTS_INTERACT_KEY + contentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        //2.如果点了赞则
        if (!redisTemplate.opsForHash().hasKey(key,hashKey)){
            throw  new BusinessException(ErrorResult.disLikeError());
        }
        //将点赞数据删除
        redisTemplate.opsForHash().delete(key,hashKey);
        //4.返回点赞数据
        Integer size = Math.toIntExact(redisTemplate.opsForHash().size(key));
        return size;
    }
}
